package com.qf.mvc.controller;

import com.qf.mvc.entity.User;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller//代表当前类是一个springMVC框架中的后端控制器类
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/test01")
    public String test01() {
        System.out.println("hello test01");
        return "/hello.jsp";
    }

    @RequestMapping("/test02")
    public String testParam1(Integer id,
                             String name,
                             Boolean gender,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date birth) {
        System.out.println(id);
        System.out.println(name);
        System.out.println(gender);
        System.out.println(birth);
        return "/hello.jsp";
    }

    @RequestMapping("/test03")
    public String test03(User user) {
        System.out.println(user);
        return "/hello.jsp";
    }

    // {id} 定义名为id的路径；【/hello/{id}】的匹配能力和【/hello/*】等价
    // http://localhost:8989/.../hello/10   {id}匹配到10
    @RequestMapping("/test04/{id}")
    // @PathVariable将{id}路径匹配到值赋给id参数
    // 路径名和参数名相同则@PathVariable("id")可简写为 @PathVariable
    public String test04(@PathVariable("id") Integer id) {
        System.out.println("id:" + id);
        return "/hello.jsp";
    }

    // http://localhost:8989/.../hello/tom   {username}匹配到tom
    @RequestMapping("/test04/{id}/{username}")
    public String test05(@PathVariable("username") String name) {//将{username}路径匹配到的值赋给name参数
        System.out.println("username:" + name);
        return "/hello.jsp";
    }
    @RequestMapping("/test06")
    public String test06(){
        System.out.println("test forward1");
        // 转发跳转 /views/users.jsp
        // return "views/users";//和下一行等价
        return "forward:/hello.jsp";// 带forward关键字则取消视图解析器的拼装过程
    }
    @RequestMapping("/test07")
    public String test07(){
        System.out.println("test forward2");
        //转发到  /forw/test1
        //return "forward:test1";//相对路径(转发到本类中的test1)
        //转发到  /forw/test1
        return "forward:test06"; //绝对路径（转发到其他controller中的方法）
    }
    @RequestMapping("/test08")
    public String test08(HttpSession session, HttpServletRequest req){
        // 调用service层的代码，执行业务逻辑处理

        // 把拿到的数据放入request或者session对象中
        User user = new User();
        user.setName("jack");
        session.setAttribute("user",user);
        req.setAttribute("age",18);
        return "forward:/hello.jsp";
    }
    @RequestMapping("/hello")
    public String test09(){
        System.out.println("进来了");
        return "/hello.jsp";
    }
}
